import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { IUser } from '@/types/user'
import { useRouter } from 'vue-router'

export const useUserStore = defineStore(
  'user',
  () => {
    // 用户信息状态
    const user = ref<IUser | null>(null)
    const token = ref<string | null>(localStorage.getItem('token'))
    const isAuthenticated = ref(!!token.value)
    const router = useRouter()
    // 方法
    const setUser = (newUser: IUser) => {
      user.value = newUser
    }

    const setToken = (newToken: string) => {
      token.value = newToken
      isAuthenticated.value = true
      sessionStorage.setItem('token', newToken)
    }

    const logout = () => {
      user.value = null
      token.value = null
      isAuthenticated.value = false
      // sessionStorage.removeItem('token')
      sessionStorage.clear()
      localStorage.clear()
      router.push('/login')
    }

    return {
      user,
      token,
      isAuthenticated,
      setUser,
      setToken,
      logout,
      currentUser: () => user.value,
    }
  },
  { persist: true },
)
